# @FileName  :  resource.py
# @Time      :  2025/8/25
# @Author    :  Your Name
# @info      :  资源CRUD操作

from typing import Optional, List
from tortoise.exceptions import DoesNotExist, IntegrityError
from app.models.models import Resource
from app.schemas.resource import ResourceCreate, ResourceUpdate, ResourceQuery


class ResourceCRUD:
    """资源CRUD操作类"""

    @staticmethod
    async def create(resource_data: ResourceCreate) -> Resource:
        """创建资源"""
        try:
            resource = await Resource.create(**resource_data.model_dump())
            await resource.fetch_related("category")
            return resource
        except IntegrityError as e:
            if "code" in str(e):
                raise ValueError("资源编码已存在")
            else:
                raise ValueError("数据完整性错误")

    @staticmethod
    async def get_by_id(resource_id: int) -> Optional[Resource]:
        """根据ID获取资源"""
        try:
            resource = await Resource.get(id=resource_id, is_deleted=False).prefetch_related("category", "teacher",
                                                                                             "course")
            # 确保teacher_name和course_name能被正确序列化
            if resource.teacher:
                resource.teacher_name = resource.teacher.name
            if resource.course:
                resource.course_name = resource.course.title
            return resource
        except DoesNotExist:
            return None

    @staticmethod
    async def get_by_code(code: str) -> Optional[Resource]:
        """根据编码获取资源"""
        try:
            resource = await Resource.get(code=code, is_deleted=False).prefetch_related("category", "teacher", "course")
            # 确保teacher_name和course_name能被正确序列化
            if resource.teacher:
                resource.teacher_name = resource.teacher.name
            if resource.course:
                resource.course_name = resource.course.title
            return resource
        except DoesNotExist:
            return None

    @staticmethod
    async def update(resource_id: int, resource_data: ResourceUpdate) -> Optional[Resource]:
        """更新资源信息"""
        try:
            resource = await Resource.get(id=resource_id, is_deleted=False).prefetch_related("category", "teacher", "course")
            update_data = resource_data.model_dump(exclude_unset=True)
            if update_data:
                await resource.update_from_dict(update_data)
                await resource.save()
                if 'category_id' in update_data:
                    await resource.fetch_related("category")
            return resource
        except DoesNotExist:
            return None
        except IntegrityError as e:
            if "code" in str(e):
                raise ValueError("资源编码已存在")
            else:
                raise ValueError("数据完整性错误")

    @staticmethod
    async def delete(resource_id: int) -> bool:
        """删除资源"""
        try:
            resource = await Resource.get(id=resource_id, is_deleted=False)
            resource.is_deleted = True
            await resource.save(update_fields=["is_deleted"])
            return True
        except DoesNotExist:
            return False

    @staticmethod
    async def get_list(query: ResourceQuery) -> tuple[List[Resource], int]:
        """获取资源列表"""
        queryset = Resource.filter(is_deleted=False).prefetch_related("category", "teacher", "course")

        # 构建查询条件
        if query.name:
            queryset = queryset.filter(name__icontains=query.name)
        if query.code:
            queryset = queryset.filter(code=query.code)
        if query.category_id:
            queryset = queryset.filter(category_id=query.category_id)
        if query.teacher_id:
            queryset = queryset.filter(teacher_id=query.teacher_id)
        if query.course_id:
            queryset = queryset.filter(course_id=query.course_id)

        # 获取总数
        total = await queryset.count()

        # 分页查询
        resources = await queryset.offset(query.skip).limit(query.limit).all()

        # 确保teacher_name和course_name能被正确序列化
        for resource in resources:
            if resource.teacher:
                resource.teacher_name = resource.teacher.name
            if resource.course:
                resource.course_name = resource.course.title

        return resources, total

    @staticmethod
    async def increment_download_count(resource_id: int) -> bool:
        """增加资源下载次数"""
        try:
            resource = await Resource.get(id=resource_id, is_deleted=False)
            resource.download_count += 1
            await resource.save(update_fields=["download_count"])
            return True
        except DoesNotExist:
            return False


# 创建全局实例
resource_crud = ResourceCRUD()
